const fs = require('fs');
const path = require('path');
const MBTiles = require('@mapbox/mbtiles');

class MBTilesService {
    constructor() {
        this.tilesDBs = {};
        this.availableTypes = [];
    }

    async init(mbtilesDir) {
        console.log(`MBTilesService: 初始化中，查找目录: ${mbtilesDir}`);
        
        if (!fs.existsSync(mbtilesDir)) {
            console.warn(`MBTilesService: 目录不存在，创建: ${mbtilesDir}`);
            fs.mkdirSync(mbtilesDir, { recursive: true });
            return;
        }

        const tileTypeMap = {
            'image': 'image.mbtiles',
            'imageLabel': 'imageLabel.mbtiles',
            'terrain': 'terrain.mbtiles',
            'terrainLabel': 'terrainLabel.mbtiles',
            'vector': 'vector.mbtiles',
            'vectorLabel': 'vectorLabel.mbtiles'
        };

        for (const [type, filename] of Object.entries(tileTypeMap)) {
            const mbtilesPath = path.join(mbtilesDir, filename);
            if (fs.existsSync(mbtilesPath)) {
                try {
                    await this._loadMBTiles(type, mbtilesPath);
                    this.availableTypes.push(type);
                    console.log(`MBTilesService: 已加载 ${type} 类型的MBTiles文件`);
                } catch (error) {
                    console.error(`MBTilesService: 加载 ${type} 类型MBTiles失败:`, error.message);
                }
            }
        }
    }

    _loadMBTiles(type, filePath) {
        return new Promise((resolve, reject) => {
            new MBTiles(filePath, (err, mbtiles) => {
                if (err) {
                    reject(err);
                    return;
                }
                
                mbtiles.getInfo((infoErr, info) => {
                    if (infoErr) {
                        reject(infoErr);
                        return;
                    }
                    
                    this.tilesDBs[type] = mbtiles;
                    resolve();
                });
            });
        });
    }

    async getTile(type, z, x, y) {
        if (!this.tilesDBs[type]) {
            return null;
        }

        // 转换XYZ坐标到TMS坐标
        //const tmsY = Math.pow(2, z) - 1 - y;
        
        return new Promise((resolve) => {
            //this.tilesDBs[type].getTile(z, x, tmsY, (err, tile) => {
            this.tilesDBs[type].getTile(z, x, y, (err, tile) => {
                if (err) {
                    resolve(null);
                    return;
                }
                resolve(tile);
            });
        });
    }

    getAvailableTypes() {
        return this.availableTypes;
    }

    close() {
        for (const [type, mbtiles] of Object.entries(this.tilesDBs)) {
            try {
                mbtiles.close();
            } catch (error) {
                console.error(`关闭MBTiles连接失败:`, error.message);
            }
        }
    }
}

module.exports = MBTilesService;